<?php
namespace App\Http\Controllers;

// use App\Http\Controllers\Controller;
use App\Http\Controllers\ArticleController;
use Illuminate\Http\Request;
use App\Models\Post;
use App\Models\Issue;
use App\Models\Article;
use App\Models\ArticleCat;
use App\Models\Author;
use App\Models\Category;
use App\Models\Collection;

/**
 *
 */
class IndexController extends Controller
{

    public function index()
    {
        $currentIssue = Issue::orderBy('volume', 'desc')->orderBy('issue', 'desc')->orderBy('id', 'desc')->first();
        $archiveIssue = Issue::where('id', '<', $currentIssue->id)
            ->orderBy('id', 'desc')
            ->limit(4)
            ->get();

        $articles = Article::where('issue_id', $currentIssue->id)->get();

        $articlesNew =[];
        $defaultCate = ArticleCat::ARTICLE_ID;
        foreach ($articles as $article) {
            if (!$article->article_cat_id) {
                $article->article_cat_id = $defaultCate;
            }

            $articlesNew[$article->articleCat->name][] = $article;
        }
        // $pictures = Article::where('is_pic', '1')->orderBy('publish_date', 'desc')->limit(6)->get();
        $pictures = Article::where('is_pic', '1')->orderBy('id', 'desc')->limit(3)->get();
        $noticeId = Category::where('slug', '=', 'notice')->first();
        $notices = Post::where('cate_id', '=', $noticeId->id)
                                 ->orderBy('updated_at', 'asc')
                                 ->limit(3)
                                 ->get();
        foreach ($notices as $key => $value) {
            $pictures[]= $value;
        }
        return view('index.index', [
            'articles' => $articlesNew,
            'current_issue' => $currentIssue,
            'news' => $this->getNews(),
            'featured' => $this->getFeatured(),
            'press' => [],
            'articles_by_download' => Article::mostDownload(),
            'articles_by_view' => Article::mostView(),
            'articles_by_wos' => Article::mostCiteOnWOS(),
            'articles_by_baidu' => Article::getBaiduCitesList(),
            'pictures' => $pictures,
            'archive_issue' => $archiveIssue,
            'collections' => Collection::online()->orderBy('created_at', 'desc')->limit(4)->get()
        ]);
    }

    public function getNews() {
        $cats = Category::where('name', '=', 'News')->get(['id']);
        foreach ($cats as $key => $value) {
            $catId = $value['id'];
        }
        $news = Post::where('cate_id', $catId)
                ->orderBy('created_at', 'asc')
                ->limit(5)
                ->get();
        return $news;
    }

    public function getFeatured() {
        return Article::where('is_featured', '1')
            ->orderBy('created_at', 'desc')
            ->first();
    }
}